package cn.xttc.edu.controller;

import cn.xttc.edu.entity.Driver;
import cn.xttc.edu.entity.ReturnMsg;
import cn.xttc.edu.entity.template.DriverStatusTemplateData;
import cn.xttc.edu.entity.template.WxTemplate;
import cn.xttc.edu.entity.template.WxTemplatesConst;
import cn.xttc.edu.service.DriverService;
import cn.xttc.edu.util.HttpUtils;
import cn.xttc.edu.util.MyUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨磊
 * @since 2022-03-09
 */
@RestController
public class DriverController {
    @Autowired
    private DriverService driverService;

    /**
     * 账号状态模板id
     */
    private final String TEMPLATEID = "9KwOMTbQiue0IVFb3uxstBCXnso5KOtcT8RC5vr0ijQ";

    /**
     * 分页获取符合条件的司机
     *
     * @param pn     页码
     * @param limit  每页显示条数
     * @param search 搜索条件
     * @param status 验证状态
     * @param sort 排序列名
     * @param order 排序方式
     * @return json字符串
     */
    @GetMapping("/driver")
    public String getAll(
            @RequestParam("page") Integer pn,
            @RequestParam("limit") Integer limit,
            @RequestParam(value = "search", required = false, defaultValue = "") String search,
            @RequestParam("verify_status[]") Integer[] status,
            @RequestParam("sort") String sort,
            @RequestParam("order") String order
    ) {
        QueryWrapper<Driver> driverWrapper = new QueryWrapper<>();
        driverWrapper.in("verify", Arrays.asList(status));
        driverWrapper.and(wrapper -> wrapper.like("name", search).or().like("phone", search));

        //得到排序列
        String sortColumn;
        switch (sort) {
            case "orderNumber":
                sortColumn = "order_number";
                break;
            case "status":
                sortColumn = "work_status";
                break;
            case "lastEditTime":
                sortColumn = "last_edit_time";
                break;
            case "verify":
                sortColumn = "verify";
                break;
            case "id":
            default:
                sortColumn = "id";
        }

        if ("asc".equalsIgnoreCase(order)) {
            driverWrapper.orderByAsc(sortColumn);
        } else if ("desc".equalsIgnoreCase(order)) {
            driverWrapper.orderByDesc(sortColumn);
        }

        Page<Driver> page = driverService.page(new Page<>(pn, limit), driverWrapper);
        return MyUtil.formatReturnData(page);
    }

    /**
     * 获取已注册司机总数
     * @return 包装对象
     */
    @GetMapping("/driver/totalNum")
    public ReturnMsg getTotalNum() {
        long count = driverService.count(new QueryWrapper<Driver>().eq("verify", 1));
        return ReturnMsg.success(count);
    }

    /**
     * 根据id更新司机状态
     *
     * @param driver 司机信息
     * @return 包装对象
     */
    @PutMapping("/driver/{id}")
    public ReturnMsg updateDriver(Driver driver) throws WxErrorException{
        Integer verify = driver.getVerify();
        Driver driver1 = driverService.getById(driver.getId());
        if (verify != null && verify == 1) {
            //设置注册时间
            driver.setRegtime(LocalDateTime.now());
        }
        try {
            driverService.updateById(driver);

            //发送模板消息
            if (verify != null) {
                //设置模板消息
                Map<String, Object> firstData = new HashMap<>();
                Map<String, Object> verifyData = new HashMap<>();
                Map<String, Object> messageData = new HashMap<>();
                Map<String, Object> remarkData = new HashMap<>();
                //填充数据
                firstData.put(WxTemplatesConst.VALUE, "您好，" + driver1.getName());
                firstData.put(WxTemplatesConst.COLOR, WxTemplatesConst.BLACK);
                messageData.put(WxTemplatesConst.COLOR, WxTemplatesConst.BLACK);
                remarkData.put(WxTemplatesConst.COLOR, WxTemplatesConst.BLACK);

                IService iService = new WxService();
                WxTemplate<DriverStatusTemplateData> driverTemplate = new WxTemplate<>();
                if (verify == 1) {
                    //通过
                    verifyData.put(WxTemplatesConst.VALUE, "已通过");
                    verifyData.put(WxTemplatesConst.COLOR, WxTemplatesConst.GREEN);
                    messageData.put(WxTemplatesConst.VALUE, "您现在可以接单了");
                    remarkData.put(WxTemplatesConst.VALUE, "");
                    //去司机首页
                    driverTemplate.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0592a476cf49a60c&redirect_uri=http://50er112323.zicp.vip/wx/driver&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
                } else if (verify == 2) {
                    //未通过
                    verifyData.put(WxTemplatesConst.VALUE, "未通过");
                    verifyData.put(WxTemplatesConst.COLOR, WxTemplatesConst.RED);
                    messageData.put(WxTemplatesConst.VALUE, "请修改后再次申请");
                    remarkData.put(WxTemplatesConst.VALUE, driver1.getRemark());
                    //去司机注册页
                    driverTemplate.setUrl("http://50er112323.zicp.vip/wx/driver_add?openid=" + driver1.getOpenId());
                }

                DriverStatusTemplateData driverStatusData = new DriverStatusTemplateData();
                driverStatusData.setFirst(firstData)
                        .setVerify(verifyData)
                        .setMessage(messageData)
                        .setRemark(remarkData);

                driverTemplate.setTemplate_id(TEMPLATEID)
                        .setTouser(driver1.getOpenId())
                        .setTopcolor(WxTemplatesConst.BLACK)
                        .setData(driverStatusData);

                String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
                url = url.replace("ACCESS_TOKEN", iService.getAccessToken());
                //发送模板消息
                HttpUtils.sendPost(url, JSON.toJSONString(driverTemplate));
            }

            return ReturnMsg.success("更新成功");
        } catch (Exception e) {
            return ReturnMsg.fail("更新失败");
        }
    }

    /**
     * 批量修改司机状态
     *
     * @param list list
     * @return 包装对象
     */
    @PutMapping("/driver")
    public ReturnMsg updateBatch(@RequestBody List<Driver> list) {
        try {
            driverService.updateBatchById(list);
            return ReturnMsg.success("修改成功");
        } catch (Exception e) {
            return ReturnMsg.fail("修改失败");
        }
    }

    /**
     * 单个删除和批量删除
     *
     * @param ids id字符串
     * @return 封装对象
     */
    @DeleteMapping("/driver/{ids}")
    public ReturnMsg deleteCars(@PathVariable("ids") String ids) {
        if (ids.contains("-")) {
            //批量删除
            List<Integer> delIds = new ArrayList<>();
            String[] strIds = ids.split("-");
            //组装id的集合
            for (String string : strIds) {
                delIds.add(Integer.parseInt(string));
            }
            try {
                driverService.removeBatchByIds(delIds);
            } catch (Exception e) {
                return ReturnMsg.fail("删除失败，该司机正在工作中");
            }
        } else {
            //单个删除
            Integer id = Integer.parseInt(ids);
            try {
                driverService.removeById(id);
            } catch (Exception e) {
                return ReturnMsg.fail("删除失败，该司机正在工作中");
            }
        }
        return ReturnMsg.success("删除成功");
    }
}

